package com.bsdsma.visonManagementSystemapp.utils;


import com.bsdsma.visonManagementSystemapp.entity.User;
import com.bsdsma.visonManagementSystemapp.service.SchoolService;
import com.bsdsma.visonManagementSystemapp.entity.Student;
import com.bsdsma.visonManagementSystemapp.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class LocalUtils {

    private static final ThreadLocal<User> USER_INFO_THREAD_LOCAL =
            new ThreadLocal<>();

    @Lazy
    @Autowired
    private SchoolService schoolService;

    private static final Logger log = LoggerFactory.getLogger(LocalUtils.class);

    /**
     * 清除用户信息
     */
    public static void clearUser() {
        USER_INFO_THREAD_LOCAL.remove();
    }

    /**
     * 存储用户信息
     */
    public static void setUser(User user) {
        USER_INFO_THREAD_LOCAL.set(user);
        log.info("Storing user in LocalUtils: {}", user);
    }

    /**
     * 获取当前用户信息
     */
    public static User getUser() {
        return USER_INFO_THREAD_LOCAL.get();
    }

    private <T extends User> void updateUserFromDto(T user, UserDto dto) {
        user.setId(dto.getId());
        user.setAccount(dto.getAccount());
        user.setPassword(dto.getPassword());
        user.setName(dto.getName());
        user.setCellphoneNumber(dto.getCellphoneNumber());
        user.setHeadImgKey(dto.getHeadImgKey());
        user.setStatus(dto.getStatus());
        user.setCt(dto.getCt());
        user.setUt(dto.getUt());

        if (user instanceof Student) {
            Student student = (Student) user;
            student.setXuexiaoId(schoolService.findByName(dto.getXuexiao()).getId());
            student.setNianji(dto.getNianji() != null ? Student.Grade.fromDisplayName(dto.getNianji()) : null);
            student.setBanji(dto.getBanji());
            student.setXuehao(dto.getXuehao());
        }
        // Add similar logic for Teacher/Admin if needed
    }

    public static void main(String[] args) {
        User currentUser = LocalUtils.getUser();
        log.info("Current user from LocalUtils: {}", currentUser);
    }
}
